package com.city.justlisten.controller;


import com.city.justlisten.entity.Consumer;
import com.city.justlisten.service.ConsumerService;
import com.city.justlisten.utils.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * 前端用户控制类
 */
@RestController
@RequestMapping("/consumer")
public class ConsumerController {

    @Autowired
    private ConsumerService consumerService;

    /**
     * 添加前端用户
     */
    @PostMapping("/add")
    public Result addConsumer(@RequestBody Consumer consumer){

        if(StringUtils.isEmpty(consumer.getUsername())){
            return Result.error().message("用户名不能为空！");
        }

        Consumer consumer1 = consumerService.getByUsername(consumer.getUsername());
        if(consumer1!=null){
            return Result.error().message("用户名已存在");
        }

        if(StringUtils.isEmpty(consumer.getPassword())){
            return Result.error().message("密码不能为空");
        }

        //把生日转换成Date格式
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Date birthDate = new Date();
        try {
            birthDate = dateFormat.parse(dateFormat.format(consumer.getBirth()));
        } catch (ParseException e) {
            e.printStackTrace();
        }

        //保存到前端用户的对象中
        consumer.setSex(new Byte(consumer.getSex()));
        consumer.setBirth(birthDate);
        boolean flag = consumerService.insert(consumer);
        if(flag){   //保存成功
            return Result.ok();
        }
        return Result.error();
    }

    /**
     * 修改前端用户
     */
    @PostMapping("/update")
    public Result updateConsumer(@RequestBody Consumer consumer){

        if(StringUtils.isEmpty(consumer.getUsername())){
            return Result.error().message("用户名不能为空！");
        }
        if(StringUtils.isEmpty(consumer.getPassword())){
            return Result.error().message("密码不能为空");
        }
        //把生日转换成Date格式
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Date birthDate = new Date();
        try {
            birthDate = dateFormat.parse(dateFormat.format(consumer.getBirth()));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        //保存到前端用户的对象中
        consumer.setSex(new Byte(consumer.getSex()));
        consumer.setBirth(birthDate);
        boolean flag = consumerService.update(consumer);
        if(flag){   //保存成功
            return Result.ok();
        }
        return Result.error();
    }


    /**
     * 删除前端用户
     */
    @GetMapping("/delete")
    public Result deleteConsumer(@RequestParam String id){
        boolean flag = consumerService.delete(Integer.parseInt(id));
        if (flag){
            return Result.ok();
        }
        return Result.error();
    }

    /**
     * 根据主键查询整个对象
     */
    @GetMapping("/selectByPrimaryKey")
    public Result selectByPrimaryKey(@RequestParam String id){
        Consumer consumer = consumerService.selectByPrimaryKey(Integer.parseInt(id));
        return Result.ok().data("consumer",consumer);
    }

    /**
     * 查询所有前端用户
     */
    @GetMapping("/allConsumer")
    public Result allConsumer(){
        List<Consumer> consumers = consumerService.allConsumer();
        return Result.ok().data("consumers",consumers);
    }

    /**
     * 更新前端用户图片
     */
    @PostMapping("/updateConsumerPic")
    public Result updateConsumerPic(@RequestParam("file") MultipartFile avatorFile, @RequestParam("id")int id){
        if(avatorFile.isEmpty()){
            return Result.error();
        }
        //文件名=当前时间到毫秒+原来的文件名
        String fileName = System.currentTimeMillis()+avatorFile.getOriginalFilename();
        //文件路径
        String filePath = System.getProperty("user.dir")+System.getProperty("file.separator")+"avatorImages";
        //如果文件路径不存在，新增该路径
        File file1 = new File(filePath);
        if(!file1.exists()){
            file1.mkdir();
        }
        //实际的文件地址
        File dest = new File(filePath+System.getProperty("file.separator")+fileName);
        //存储到数据库里的相对文件地址
        String storeAvatorPath = "/avatorImages/"+fileName;
        try {
            avatorFile.transferTo(dest);
            Consumer consumer = new Consumer();
            consumer.setId(id);
            consumer.setAvator(storeAvatorPath);
            boolean flag = consumerService.update(consumer);
            if(flag){
                return Result.ok().data("avator",storeAvatorPath);
            }
            return Result.error();
        } catch (IOException e) {
            return Result.error();
        }
    }

    /**
     * 前端用户登录
     */
    @PostMapping("/login")
    public Result login(HttpServletRequest request){
        String username = request.getParameter("username").trim();     //账号
        String password = request.getParameter("password").trim();     //密码
        if(username==null||username.equals("")){
            return Result.error();
        }
        if(password==null||password.equals("")){
            return Result.error();
        }

        //保存到前端用户的对象中
        Consumer consumer = new Consumer();
        consumer.setUsername(username);
        consumer.setPassword(password);
        boolean flag = consumerService.verifyPassword(username,password);
        if(flag){   //验证成功
            return Result.ok().data("userMsg",consumerService.getByUsername(username));
        }
        return Result.error();
    }
}